import Config from "../Config";
import dayjs from "dayjs";
import {isBlank, isObject} from "./index";

/**
 * 向url中添加参数
 * @param url
 * @param params 要添加的参数对象 {参数名: 参数值}
 * @param isUrl 是否自动判断增加问号 默认true
 * @return {*} 拼接好的url
 */
// @ts-ignore
const addUrlParams: Function = (url: string, params: object, isUrl: boolean): string => {
    let urlParams: object = parseUrlParams(url),
        newParams: any = {...urlParams, ...params};
    if (isUrl && url.indexOf("?") === -1) {
        url += "?";
    } else {
        url = url.split("?")[0] + "?"
    }
    for (let item in newParams) {
        let value = newParams[item];
        if (isBlank(value)) {
            value = "";
        }
        if (isObject(value)) {
            if (dayjs.isDayjs(value)) {
                value = dayjs(value, Config.dateFormat.date);
            } else {
                value = JSON.stringify(value);
            }
        }
        if (!url || (url.substr(url.length - 1) !== "&" && url.substr(url.length - 1) !== "?")) {
            url += "&";
        }
        url += decodeURIComponent(item) + "=" + encodeURIComponent(value);
    }
    return url;
};

/**
 * 解析url中拼接的参数
 * @param url
 * @return {{参数名: string}}
 */
// @ts-ignore
const parseUrlParams: Function = (url: string): object => {
    if (url.indexOf("?") !== -1) {
        url = url.substr(url.indexOf("?") + 1);
    }
    //eslint-disable-next-line
    let paramsArr = url.match(/[^\?\=\&]*\=[^\?\=\&]*/g);
    let params: any = {};
    if (paramsArr != null) {
        paramsArr.forEach(item => {
            let kv = item.split("=");
            params[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
        });
    }
    return params;
};

// @ts-ignore
const getComUrl: Function = (data: any): string => {
    const {url = "", key, isOutside = false}: { url: string, key: string, isOutside: boolean } = data;

    let newUrl: string;

    if (isOutside) {
        newUrl = url;
    } else {
        newUrl = window.location.origin + (key ? ("/home/" + key) : url);
    }

    return newUrl;
};

export {
    addUrlParams,
    parseUrlParams,
    getComUrl
};